import {
  Injectable,
  ExecutionContext,
  CallHandler,
  Logger,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import * as path from 'path';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../auth/auth.decorator';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger(LoggingInterceptor.name);

  constructor(private reflector: Reflector) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const fileName = path.basename(__filename);
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    this.logger.log(
      `请求接口为: ${request.url},请求方法为: ${request.method}, 是否为公共接口: ${!!isPublic}`,
    );

    return next.handle().pipe(
      tap(() => {
        // 你可以在这里做其他的日志操作，例如响应后再记录日志
        this.logger.log(`响应接口: ${request.url} 已完成`);
      }),
    );
  }
}
